package org.example.service.impl;
/*
* fzl
* */
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import org.example.domain.model.Result;
import org.example.prop.OssProperties;
import org.example.service.OssService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Service
public class OssServiceImpl implements OssService {


    @Resource
    private OssProperties ossProperties;

    public OssServiceImpl() {
    }

    //前端文件上传
    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",".jpeg", ".gif", ".png",".jpe"};
    @Override
    public Result upload(MultipartFile uploadFile) throws Exception {
        OSS ossClient = (new OSSClientBuilder()).build(ossProperties.getEndpoint(), ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
        // 校验图片格式
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),
                    type)) {
                isLegal = true;
                break;
            }
        }
        if (!isLegal) {
            return Result.buildFail("图片格式不符");
        }
        //获取文件输入流
        InputStream is = new ByteArrayInputStream(uploadFile.getBytes());

        /*文件名处理*/
        //获取文件原名
        String fileName =uploadFile.getOriginalFilename();
        // 获取文件的后缀(如.jpg,.png)
        String suffixOfFileName = fileName.substring(fileName.lastIndexOf("."));
        //生成新的文件名 如202111032222xxxxxxx
        String newFileName = DateUtil.format(LocalDateTime.now(), "yyyyMMddHHmmss") + RandomUtil.randomString(6) + suffixOfFileName;
        //生成目标路径
        String targetPath = ossProperties.getDirPrefix()+newFileName;
        //生成图片访问路径
        String picUrl =ossProperties.getBucketURL() + newFileName;
        //设置文件元信息,以便于图片能通过路径直接访问,而非强制下载
        ObjectMetadata meta = new ObjectMetadata();
        switch (suffixOfFileName){
            case ".jpg": case".jpeg":case".jpe":
                meta.setContentType("image/jpeg");
                break;
            case ".png":
                meta.setContentType("image/png");
                break;
            case ".gif":
                meta.setContentType("image/gif");
                break;
            case ".bmp":
                meta.setContentType("image/bmp");
                break;
        }
        // 设置内容被下载(attachment)/被预览(inline)。
        meta.setContentDisposition("inline");



        //上传到阿里云
        try {
            ossClient.putObject(ossProperties.getBucketName(), targetPath, is, meta);
        }catch (Exception e){
            return Result.buildFail("文件上传失败");
        }
        //将上传图片的相关信息传回
        Map<String,Object> fileInfo = new HashMap<>();
        fileInfo.put("oldname",fileName);
        fileInfo.put("newName",newFileName);
        fileInfo.put("uploadTime",LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        fileInfo.put("picUrl",picUrl);
        return Result.buildSuccess(fileInfo);
    }
}
